﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Configuration.Install;
using System.Configuration;

namespace Chisholm.Windows.Live.SSOServer
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                bool activeargument = false;
                foreach (string thisarg in args)
                {
                    if (thisarg.Contains("help"))
                    {
                        // Write out the help to the command line
                        Console.WriteLine("Chisholm Institute SSO Server Service - Console Mode Help");
                        Console.WriteLine("This application can be installed / uninstalled / run in console mode by doing the following:");
                        Console.WriteLine("/install");
                        Console.WriteLine(">> This will install the service.");
                        Console.WriteLine("/uninstall");
                        Console.WriteLine(">> This will uninstall an existing service.");
                        Console.WriteLine("/console");
                        Console.WriteLine(">> This will run the service in console mode.");
                        Console.WriteLine("/help");
                        Console.WriteLine(">> This will show the help commands (this output).");
                        activeargument = true;
                    }
                    else if (thisarg.Contains("/install"))
                    {
                        // First see if we can split the install parameter to grab the name of the service
                        TransactedInstaller ti = new TransactedInstaller();
                        ProjectInstaller pi = new ProjectInstaller();

                        ((ServiceInstaller)pi.Installers[1]).ServiceName = "Windows Live SSO Server";
                        ((ServiceInstaller)pi.Installers[1]).DisplayName = "Windows Live SSO Server";

                        ti.Installers.Add(pi);
                        string path = String.Format("/assemblypath={0}",
                            System.Reflection.Assembly.GetExecutingAssembly().Location);
                        string[] cmdline = { path };
                        InstallContext ctx = new InstallContext("", cmdline);
                        ti.Context = ctx;
                        ti.Install(new System.Collections.Hashtable());
                        activeargument = true;
                    }
                    else if (thisarg.Contains("/uninstall"))
                    {
                        // First see if we can split the install parameter to grab the name of the service
                        TransactedInstaller ti = new TransactedInstaller();
                        ProjectInstaller pi = new ProjectInstaller();

                        ((ServiceInstaller)pi.Installers[1]).ServiceName = "Windows Live SSO Server";
                        ((ServiceInstaller)pi.Installers[1]).DisplayName = "Windows Live SSO Server";

                        ti.Installers.Add(pi);
                        string path = String.Format("/assemblypath={0}",
                            System.Reflection.Assembly.GetExecutingAssembly().Location);
                        string[] cmdline = { path };
                        InstallContext ctx = new InstallContext("", cmdline);
                        ti.Context = ctx;
                        ti.Uninstall(null);
                        activeargument = true;
                    }
                    else if (thisarg.Contains("/console"))
                    {
                        // Read the service configuration and start the service
                        Console.WriteLine("SSO Server Service starting in console mode...");
                        Console.WriteLine("------------------------------------------------------------------------");
                        Console.WriteLine("The service is being provided on the following port:");
                        Console.WriteLine("net.tcp://" + ConfigurationManager.AppSettings["Server"] +
                            ":" + ConfigurationManager.AppSettings["Port"] + "/SSOServer");                        
                        
                        // Indicate that the service is active
                        activeargument = true;

                        // Start the service
                        List<string> errors = ServiceManager.StartService();
                        if (errors.Count > 0)
                        {
                            Console.WriteLine("------------------------------------------------------------------------");
                            Console.WriteLine("Some errors occured while trying to start the service. They were: ");
                            foreach (string thiserror in errors)
                                Console.WriteLine(thiserror);
                            Console.WriteLine("Press the ESCAPE key to exit.");
                        }
                        else
                        {
                            Console.WriteLine("------------------------------------------------------------------------");
                            Console.WriteLine("The service is now operational. To close the service, press the ESCAPE key.");
                        }

                        // Wait for the user to cancel the service
                        ConsoleKey keypressed = ConsoleKey.A;
                        while (keypressed != ConsoleKey.Escape)
                        {
                            keypressed = Console.ReadKey().Key;
                        }

                        // Close the service
                        ServiceManager.StopService();
                    }
                }

                // Check to see if the service was active, otherwise start the base service
                if (!activeargument)
                {
                    ServiceBase[] ServicesToRun;
                    ServicesToRun = new ServiceBase[] 
			    { 
				    new SSOServer()
			    };
                    ServiceBase.Run(ServicesToRun);
                }
            }
            else
            {
                // No arguments were supplied so start the service
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
			    { 
				    new SSOServer()
			    };
                ServiceBase.Run(ServicesToRun);
            }
        }
    }
}
